package com.zhang.third.day02;

import com.zhang.third.utils.IntegerStatistic;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple5;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @title: process 求 max min avg sum count
 * @author: zhang
 * @date: 2022/4/2 16:03
 */
public class ReduceWithProcess {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .fromElements(1, 3, 2, 5, 7, 2, 5, 4, 3, 2, 9)
                .keyBy(r -> 1)
                .process(new KeyedProcessFunction<Integer, Integer, IntegerStatistic>() {

                    // 声明累加器值状态变量
                    private ValueState<IntegerStatistic> accumulator;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        // 初始化累加器
                        accumulator = getRuntimeContext().getState(
                                new ValueStateDescriptor<IntegerStatistic>(
                                        "int-state", Types.POJO(IntegerStatistic.class)
                                )
                        );
                    }

                    @Override
                    public void processElement(Integer value, KeyedProcessFunction<Integer, Integer, IntegerStatistic>.Context ctx, Collector<IntegerStatistic> out) throws Exception {
                        // 当第一条数据来的时候直接更新累加器，数据直接丢弃，然后输出累加器
                        if (accumulator.value() == null) {
                            accumulator.update(new IntegerStatistic(
                                    value, value, value, 1, value
                            ));
                            //第二天数据及以后数据到来的时候，与累加器做聚合，然后更新累加器并输出累加器
                        } else {
                            IntegerStatistic tmp = accumulator.value();
                            accumulator.update(new IntegerStatistic(
                                    Math.max(value, tmp.max),
                                    Math.min(value, tmp.min),
                                    value + tmp.sum,
                                    tmp.count + 1,
                                    (value + tmp.sum) / (tmp.count + 1)
                            ));
                        }
                        // 往下游发送结果
                        out.collect(accumulator.value());
                    }
                })
                .print();

        env.execute();
    }
}
